Association classes

Associations define the relationship between Classes. Whenever you need additional information on that relationship, association classes will come in handy.

Model 1:

Model 1 Association classes.png

Even if the Association class is often used for many to many relationships, you can use them on the association of any cardinality.

Model 2:

Model 2 Association classes.png

OR-mapping (the process of taking an object-oriented model (a standard UML class diagram) and transforming it into a relational database schema (tables, fields, primary and foreign keys) ) will turn this model into three tables; one to store Person, one to store Flight and one to store Booking.

If you had not used the association class, OR-mapping would still create three tables due to the many-to-many associations. The third table would store two foreign keys, one to identify the Person and one to identify the Flight. The third table would implicitly be named, if you did not explicitly give it a name, to PersonFlight or FlightPerson. This table the DB-guys often refer to as a link table.

The funny thing is that modeling this another way will give the same OR-Mapping result:

Model 3:

Model 3 Association classes.png

This will also end up in the database as three tables where Booking points out Person and Flight with one foreign key for each. So for a DB-centric guy, this is the same… To an OO guy, this is NOT the same.

What is the Difference?

The rules that association classes adhere to in any well-behaving MDD framework are these:

  1. Lifetime control: The booking cannot be explicitly created. It is created as a consequence of associating a Person with a Flight: aPerson.Flights.Add(aFlight). It is destroyed automatically whenever the association is removed: aPerson.Flights.Remove(aFlight)
  2. Uniqueness: In UML, one instance must be unique in the relation; you cannot add one person to a flight twice. This way, using the association class has effectively given the UML reader the information that a person can only be one passenger at a time - not two.

Whenever you see the need for lifetime control and uniqueness, use the association class. It will help the reader and the developer – the DB guy will not know the difference - however, they seldom do.

(Side note: Entity Framework does not currently support association classes. They argue there is no need since the Model2 can be replaced with Model3 (No surprise since they are DB guys.).)

Adding a Link Object

Look at Adding a link object for an example of EAL to help you easily handle adding a link object.

The MDriven Book - Next Chapter: UML Inheritance

This page was edited 46 days ago on 10/02/2024. What links here